﻿using System;
using System.IO;
using System.Security.Cryptography;

namespace Adams.Web.Logic
{
    public class Email
    {
        public static void QueueEmail(string subject, string from, string to, string body, int priority)
        {
            Data.Email.QueueEmail(subject, from, to, body, priority);      
        }

        public static string GetEmailFromCode(string code)
        {
            string en = Shared.Crypt.Decrypt(code);
            string email = en.Split('|')[0];
            return email;
        }

        public static string GenerateSignupEmail(string email)
        {
            string templatepath = Shared.Config.GetAppSetting("EmailTemplatesPath").TrimEnd('\\') + "\\signup.htm";
            string body = Shared.IOHelper.GetFileContents(templatepath);
            string code = Shared.Crypt.Encrypt(email + "|" + DateTime.Now.ToString());
            code = System.Web.HttpUtility.UrlEncode(code);
            string url = Shared.Config.GetAppSetting("BaseUrl").TrimEnd('/') + "/Security/ConfirmEmail?Code=" + code;
            body = body.Replace("[URL]", url);
            body = body.Replace("[EMAIL]", email);
            return body;
        }

        public static string GenerateForgotEmail(string email)
        {
            string templatepath = Shared.Config.GetAppSetting("EmailTemplatesPath").TrimEnd('\\') + "\\forgot.htm";
            string body = Shared.IOHelper.GetFileContents(templatepath);
            string code = Shared.Crypt.Encrypt(email + "|" + DateTime.Now.ToString());
            code = System.Web.HttpUtility.UrlEncode(code);
            string url = Shared.Config.GetAppSetting("BaseUrl").TrimEnd('/') + "/Security/PasswordReset?Code=" + code;
            body = body.Replace("[URL]", url);
            body = body.Replace("[EMAIL]", email);
            return body;
        }

        public static string GeneratePasswordResetCompleteEmail(string email)
        {
            string templatepath = Shared.Config.GetAppSetting("EmailTemplatesPath").TrimEnd('\\') + "\\forgotcomplete.htm";
            string body = Shared.IOHelper.GetFileContents(templatepath);
            body = body.Replace("[EMAIL]", email);
            return body;
        }

        public static string GenerateChangeEmail(string email)
        {
            string templatepath = Shared.Config.GetAppSetting("EmailTemplatesPath").TrimEnd('\\') + "\\changeemail.htm";
            string body = Shared.IOHelper.GetFileContents(templatepath);
            string code = Shared.Crypt.Encrypt(email + "|" + DateTime.Now.ToString());
            code = System.Web.HttpUtility.UrlEncode(code);
            string url = Shared.Config.GetAppSetting("BaseUrl").TrimEnd('/') + "/Security/ConfirmEmail?Code=" + code;
            body = body.Replace("[URL]", url);
            body = body.Replace("[EMAIL]", email);
            return body;
        }
    }
}